package com.zhixianggou.caibaobox.user.login;

import com.zhixianggou.caibaobox.commons.result.ReturnCodeEnum;
import com.zhixianggou.caibaobox.commons.result.ReturnData;
import com.zhixianggou.caibaobox.user.dto.UserAuthDto;
import com.zhixianggou.caibaobox.user.service.UserAuthService;
import com.zhixianggou.caibaobox.user.shiro.tokens.PhonePwdToken;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zyq
 * 8/22/24 11:19 AM
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    UserAuthService userAuthService;

    /**
     * 账号注册
     * @param dto
     * @return
     */
    @RequestMapping(value = "/register")
    public ReturnData register(@RequestBody UserAuthDto dto) {
        return userAuthService.register(dto);
    }

    /**
     * 账号登录
     * @param dto
     * @return
     */
    @RequestMapping("/login")
    public ReturnData login(@RequestBody UserAuthDto dto) {
        try{
            Subject subject = SecurityUtils.getSubject();
            PhonePwdToken token = new PhonePwdToken(dto.getAccount(), dto.getLoginPwd());
            subject.login(token);
            return ReturnData.success();
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            return ReturnData.fail(ReturnCodeEnum.ACCOUNT_EXISTS_ERROR);
        }catch (DisabledAccountException e) {
            return ReturnData.fail(ReturnCodeEnum.RC403);
        }catch (Exception e) {
            e.printStackTrace();
            return ReturnData.fail(ReturnCodeEnum.RC500);
        }catch (Throwable throwable) {
            return ReturnData.fail(ReturnCodeEnum.RC500);
        }
    }

    /**
     *  账号退出
     * @return
     */
    @RequestMapping("/logout")
    public ReturnData logout() {
        try{
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return ReturnData.success();
        }catch (Exception e) {
            e.printStackTrace();
            return ReturnData.fail(ReturnCodeEnum.RC500);
        }
    }
}
